from django.shortcuts import render,redirect,HttpResponse
from django.contrib.auth.decorators import login_required
from kingadmin import app_setup
from django.db.models import Q
import re
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
app_setup.kingadmin_auto_discover()
# Create your views here.
from kingadmin.permissions import check_per
from kingadmin.sites import site
print(site.enabled_admins)
def index(request):
    print(site.enabled_admins)
    return render(request, 'temp/app_index.html',{'site':site})

def filter_data(request,data):
    filter_dict={}
    for k,v in request.GET.items():
        if k in ('_q','p','_o'):continue
        if v:
            filter_dict[k]=v
    data_obj=data.filter(**filter_dict)
    return data_obj,filter_dict
def search(request,querysets,admin_class):
    if request.GET.get('_q'):
        search_field=request.GET.get('_q')

        q=Q()
        q.connector='OR'
        for i in admin_class.search_fields:
            #处理choices字段，(0,'qq群')
            if not re.search('.*__.*',i):#如果搜索字段中包含库表查询，那么放弃choices字段查询
                try:

                    choices_list=admin_class.model._meta.get_field(i).get_choices()
                    print('choices_list',choices_list)
                    for i2 in choices_list:
                        if i2[1] == search_field:
                            search_field=i2[0]
                except AttributeError:
                    choices_list=None

            q.children.append(('%s__contains'%i,search_field))
        admin_class.search_fieldd = request.GET.get('_q')
        return querysets.filter(q),admin_class
    else:
        admin_class.search_fieldd = ""
        return querysets,admin_class
def sort(request,queryset,admin_class):
    sort_id=request.GET.get('_o')
    if sort_id:
        admin_class.sort_id=sort_id

        if sort_id.startswith('-'):
            sort_field=admin_class.list_display[abs(int(sort_id))]

        else:

            sort_field='-%s'%admin_class.list_display[abs(int(sort_id))]
        return  queryset.order_by(sort_field),admin_class

    else:
        admin_class.sort_id=''
        return queryset,admin_class

@check_per
def table_obj_list(request,app_name,model_name):

    admin_class=site.enabled_admins[app_name][model_name]
    querysets=admin_class.model.objects.all()
    import json
    if request.method == 'POST':
        actions_list=json.loads(request.POST.get('actions_list'))
        action=request.POST.get('action')
        querySet=admin_class.model.objects.filter(id__in=actions_list)
        actions=getattr(admin_class,action)
        actions(request,querySet)
        index_page="/kingadmin/%s/%s"%(app_name,model_name)
        return redirect(index_page)
    else:
        #filter
        querysets,filter_dict=filter_data(request,querysets)
        admin_class.filter_dict=filter_dict
        #search
        querysets,admin_class=search(request,querysets,admin_class)
        #sort
        querysets,admin_class=sort(request,querysets,admin_class)
        #paginator
        p=Paginator(querysets,4)
        admin_class.p=p
        page=request.GET.get('p')
        admin_class.p_num=page
        try:
            querysets=p.page(page)
        except EmptyPage:
            querysets=p.page(1)
        except PageNotAnInteger:
            querysets=p.page(1)

        return render(request,'temp/table_obj_list.html',{"querysets":querysets,'admin_class':admin_class,'appname'\
            :app_name,'model_name':model_name})

@check_per
def table_obj_change(request,app_name,model_name,filed_id):
    admin_class=site.enabled_admins[app_name][model_name]
    from kingadmin.form_handle import haldle_model
    model_form=haldle_model(admin_class)
    obj=admin_class.model.objects.get(id=filed_id)
    if request.method == 'GET':
        form_obj=model_form(instance=obj)
    elif request.method == 'POST':
        print(request.POST)
        form_obj=model_form(instance=obj,data=request.POST)
        if form_obj.is_valid():
            form_obj.save()
            url='/kingadmin/%s/%s'%(app_name,model_name)
            return redirect(url)

    return render(request,'temp/table_obj_change.html',locals())

def infoask(request):
    from kingadmin import Form
    from crm import models
    obj=models.CustomerInfo.objects.get(id=13)
    form_obj=Form.form(instance=obj)
    if request.method == 'POST':
        form_obj=Form.form(instance=obj,data=request.POST)

        if form_obj.is_valid():
            form_obj.save()
            return redirect('/kingadmin/1')

    return render(request,'temp/infoask.html',locals())